package com.casic.common.ibatis.typeHandler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeException;
import org.apache.ibatis.type.TypeHandler;

import java.io.StringReader;
import java.sql.*;


/**
 * @Company 航天科技山西公司
 * @Project hitech-Common
 * @Package com.hitech.ibatis.typeHandler
 * @ClassName ClobTypeHandler.java
 * @Description TODO(ClobTypeHandler)
 * @author yangying
 * @create 2016年9月21日-下午5:13:24
 */
public class ClobTypeHandler implements TypeHandler<String> {

	@Override
	public String getResult(ResultSet arg0, String arg1) throws SQLException {
		// TODO Auto-generated method stub
		 if(arg0.wasNull()){
			 return null;
		 }
		 String value = "";
		 Clob clob = arg0.getClob(arg1);
		 if (clob != null) {
		      int size = (int) clob.length();
		      value = clob.getSubString(1, size);
		  }
		 return value;
	}

	@Override
	public String getResult(ResultSet arg0, int arg1) throws SQLException {
		// TODO Auto-generated method stub
	    if (arg0.wasNull()) {
	      return null;
	    } 
	    String value = "";
	    Clob clob = arg0.getClob(arg1);
	    if (clob != null) {
	      int size = (int) clob.length();
	      value = clob.getSubString(1, size);
	    }
	    return value;
	}

	@Override
	public String getResult(CallableStatement arg0, int arg1)
			throws SQLException {
		// TODO Auto-generated method stub
	    if (arg0.wasNull()) {
	      return null;
	    }
	    String value = "";
	    Clob clob = arg0.getClob(arg1);
	    if (clob != null) {
	      int size = (int) clob.length();
	      value = clob.getSubString(1, size);
	    }
	    return value;
	    
	}

	@Override
	public void setParameter(PreparedStatement arg0, int arg1, String arg2,
			JdbcType arg3) throws SQLException {
		// TODO Auto-generated method stub
		if (arg2 == null) {
	      if (arg3 == null) {
	        throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
	      }
	      try {
	    	  arg0.setNull(arg1, arg3.TYPE_CODE);
	      } catch (SQLException e) {
	        throw new TypeException("Error setting null for parameter #" + arg1 + " with JdbcType " + arg3 + " . " +
	        		"Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
	        		"Cause: " + e, e);
	      }
	    } else {
	    	StringReader reader = new StringReader(arg2);
	    	arg0.setCharacterStream(arg1, reader, arg2.length());
	    }
	}

  

}
